// pages/child_info/index.js
import { getData } from "../mine/function";


const db = wx.cloud.database();
const _ = db.command;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    donorInfo: "",
    curChild: "",
    selectedIndex_toDonoteChild: -1,
    selectedIndex_payway: -1,
    donateMoney: "",
    moneys: [20, 50, 100, 200],
    donateType: "",
    types: ['每月支付', '一次支付'],
    showIndex: null,

    showDialog: false,
  },

  // ---------------------原生---------------------
  toContribution() {
    wx.navigateTo({
      url: '/pages/contribution/index',
    })
  },
  openPopup(e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      showIndex: index
    })
  },
  closePopup() {
    this.setData({
      showIndex: null
    })
  },

  // ---------------------前端数据渲染---------------------
  onMoneyButtonTap(event) {
    const { index, selected } = event.currentTarget.dataset;
    //console.log(index,selected);
    if (selected) {
      return; // 如果按钮已经选中，则不执行任何操作
    }
    this.setData({
      selectedIndex_toDonoteChild: index
    });
  },
  onPaymentButtonTap(event) {
    const { index } = event.currentTarget.dataset;
    console.log(index);
    this.setData({
      selectedIndex_payway: index
    });
  },

  // ---------------------util---------------------
  getLocalDate() {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const date = now.getDate();
    const formattedDate = `${year}.${month.toString().padStart(2, '0')}.${date.toString().padStart(2, '0')}`;
    return formattedDate;
    // const now = new Date();
    // return now.toLocaleDateString('zh-CN');
  },
  async init() {
    var res = await getData("ourOx68K-yzP1JGUbwnM9FAEJ8hA");
    console.log(res);
    this.setData({
      donorInfo: res,
      donatedChildren: res.students,
    })
    // console.log("donorInfo")
    // console.log(this.data.donorInfo)
  },

  // ---------------------捐款模块---------------------



  async confirmPay(event) {
    this.data.showDialog = true;
    console.log(this.data.showDialog)
    this.data.donateMoney = this.data.moneys[this.data.selectedIndex_toDonoteChild]

    db.collection('childInfo').where({
      studentName: this.data.curChild.studentName
    }).update({
      data: {
        times: this.data.curChild.times + 1
      }
    }).then(res => {
      console.log("timesLog")
      console.log(res)
    })

    // const donorRes = await db.collection('donor').doc('f18e14fa6543438604a4c12e76abaa0f').get();
    // const donorInfo = donorRes.data;
    const donorInfo = this.data.donorInfo;

    var totalDonation = donorInfo.totalDonation || {}; // 如果字段不存在则创建一个空对象
    totalDonation['nov'] = (totalDonation['nov'] || 0) + this.data.donateMoney;

    var donorStudentsRes = await db.collection('donor').doc(donorInfo._id).get();
    var donorStudents = donorStudentsRes.data.students;

    console.log("donorStudents");
    console.log(donorStudents);

    const selectedStudentIndex = donorStudents.findIndex(student => student.name === this.data.curChild.studentName);
    if (selectedStudentIndex === -1) {
      console.log("尚未捐助过该学生");

      var newChild = {
        date: this.getLocalDate(),
        imgUrl: this.data.curChild.imgUrl,
        name: this.data.curChild.studentName,
        province: this.data.curChild.province,
        tag: this.data.curChild.tag,
        money: this.data.donateMoney,
        times: 1,
      }


      donorStudents.push(newChild);
      db.collection('donor').doc("f18e14fa6543438604a4c12e76abaa0f").update({
        data: {
          times: _.inc(1),
          credit: _.inc(this.data.donateMoney * 0.2),
          students: donorStudents,
          totalDonation: totalDonation
        }
      });

      this.setData({
        showDialog: true,
      })
    } else {
      console.log("拿到了捐助过的这名学生的信息");
      console.log(donorStudents[selectedStudentIndex])
      donorStudents[selectedStudentIndex].times += 1;
      donorStudents[selectedStudentIndex].money += this.data.donateMoney;

      const updateDonorRes = await db.collection('donor').doc("f18e14fa6543438604a4c12e76abaa0f").update({
        data: {
          times: _.inc(1),
          credit: _.inc(this.data.donateMoney * 0.2),
          students: donorStudents,
          totalDonation: totalDonation
        }
      });

      console.log(updateDonorRes);

      this.setData({
        showDialog: true,
      })
    }
  },

  // ---------------------utils---------------------
  // 计算年龄
  getAge(birthDateString) {
    var today = new Date();
    var birthDate = new Date(birthDateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var monthDiff = today.getMonth() - birthDate.getMonth();

    // 如果当前月份小于出生月份，或者当前月份等于出生月份但是当前日期小于出生日期，则年龄减一
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
      age--;
    }

    return age;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.init()

    var that = this
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on("childInfo", function (data) {
      // 设置更好用的信息
      var child = data.data;
      child.age = that.getAge(child.birthday)
      var parts = child.questionAnswer.split("_")
      child.question = parts[0]
      child.answer = parts[1]

      that.setData({
        curChild: child
      })
      console.log(child)

    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.init()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})